package com.gcloud.mesh.analysis.arima;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ARIMAManager {

	@Value("${mesh.analysis.ariam:false}")
	private boolean ariamEnabled;
	
	private List<Double> data = new ArrayList<Double>();
	
	private ARIMA arima = null;
	
	public synchronized Double predict(Double point) {
		Double predictValue = point;
		if(ariamEnabled) {
			initData(point);
			double[] newData = new double[data.size()];
			for(int i=0; i<data.size(); i++) {
				newData[i] = data.get(i);
			}
			ARIMA newArima=new ARIMA(newData); 
			if(getAccuracy(newArima, data) > getAccuracy(arima, data)) {
				arima = newArima;
			}
			predictValue = getPredictValue(arima);
		}
		
		return predictValue;
	}
	
	private synchronized void initData(Double point) {
		if(data.size() >= 60) {
			data.remove(0);
			data.add(point);
		}
	}
	
	private double getAccuracy(ARIMA arimaModel, List<Double> data) {
		if(arimaModel != null) {
			int []model=arimaModel.getARIMAmodel();
			double value = (arimaModel.aftDeal(arimaModel.predictValue(model[0],model[1]))-data.get(data.size()-1))/data.get(data.size()-1)*100;
			return value;
		}
		return 0;
	}
	
	private double getPredictValue(ARIMA arimaModel) {
		if(arimaModel != null) {
			int []model=arimaModel.getARIMAmodel();
			double value = arimaModel.aftDeal(arimaModel.predictValue(model[0],model[1]));
			return value;
		}
		return 0;
	}
	
}
